package com.bawei.mvidemo

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.mvidemo.http.ApiResponse
import com.bawei.mvidemo.http.MyService
import com.bawei.mvidemo.http.RetrofitManger
import com.bawei.mvidemo.http.VideoEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/17 09:31
 * @Description : MyViewModel
 */
class MyViewModel:ViewModel() {
    val newsChannel = Channel<MyIntent>(Channel.UNLIMITED)//通道，泛型意图
    private val _uiState = MutableStateFlow<MyUIState>(MyUIState.Success(null))//UI状态，默认是成功 数据为null
    val uiState: StateFlow<MyUIState> = _uiState  //StateFlow 留


    init{
        handleIntent()
    }
    //2：处理用户发过来的intent:通过通道发送来的
    private fun handleIntent() {
        viewModelScope.launch {
            newsChannel.consumeAsFlow().collect{
                when(it){
                    is MyIntent.GetVideos -> getVideoData() //请求视频数据
                }
            }
        }
    }
    //4：请求数据并更新UIState
    private fun getVideoData() {
        viewModelScope.launch {
            myVideos.flowOn(Dispatchers.Default)//切换到默认的主线程中
                    //捕获异常
                .catch { exception->
                    _uiState.value = MyUIState.Error(exception)
                    //过滤
                }.filter {
                    it.data != null
                    //收集结果
                }.collect{
                    _uiState.value = MyUIState.Success(it.data)
                }
        }

    }
    //3：retrofit请求数据，使用流发射出去，流里有数据
    private var  myVideos = flow<ApiResponse<MutableList<VideoEntity>>> {
        val videos = RetrofitManger.getRetrofit().create(MyService::class.java).videos(1, 10)
        emit(videos)//
    }




}